import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'nft_transaction_confirm_screen.dart';

class NFTTradeScreen extends StatefulWidget {
  const NFTTradeScreen({Key? key}) : super(key: key);

  @override
  State<NFTTradeScreen> createState() => _NFTTradeScreenState();
}

class _NFTTradeScreenState extends State<NFTTradeScreen> {
  // 筛选状态
  String _selectedFilter = '全部';
  // 搜索文本
  String _searchText = '';
  // 加载状态
  bool _isLoading = true;
  // 模拟NFT数据
  late List<Map<String, dynamic>> nfts;
  // 过滤后显示的NFT数据
  late List<Map<String, dynamic>> _filteredNfts;
  // 排名类型状态
  String _rankingType = '价格排名';

  @override
  void initState() {
    super.initState();
    // 模拟API加载延迟
    _loadNFTs();
  }


  
  // 切换排名类型
  void _switchRankingType(String rankingType) {
    setState(() {
      _rankingType = rankingType;
      _applyFilters(); // 重新应用筛选
    });
  }

  // 加载NFT数据
  void _loadNFTs() {
    // 模拟API请求延迟
    Future.delayed(const Duration(seconds: 1), () {
      if (mounted) {
        setState(() {
        // 模拟NFT数据
        nfts = [
          // NFT购买数据
          {
            'name': '苏绣非遗传承人作品',
            'author': '张明',
            'price': '15800',
            'ranking': 1,
            'tradeType': 'buy',
            'imageUrl': 'assets/images/nft/suzhou_embroidery.svg',
            'category': '苏绣',
            'categoryText': '苏绣',
            'categoryBgColor': const Color(0xFFE6F7FF),
            'categoryTextColor': const Color(0xFF1890FF),
            'artworkName': '《牡丹图》',
            'volume': '1,250',
            'change': '+12.5%',
          },
          {
            'name': '景德镇陶瓷艺术',
            'author': '王芳',
            'price': '28600',
            'ranking': 2,
            'tradeType': 'buy',
            'imageUrl': 'assets/images/nft/ceramic_culture.svg',
            'category': '陶瓷',
            'categoryText': '陶瓷',
            'categoryBgColor': const Color(0xFFFFF7E0),
            'categoryTextColor': const Color(0xFFFA8C16),
            'artworkName': '《青花瓷》',
            'volume': '980',
            'change': '+8.3%',
          },
          {
            'name': '中国传统剪纸艺术',
            'author': '李红',
            'price': '8900',
            'ranking': 3,
            'tradeType': 'buy',
            'imageUrl': 'assets/images/nft/paper_cutting.svg',
            'category': '剪纸',
            'categoryText': '剪纸',
            'categoryBgColor': const Color(0xFFFFF0F0),
            'categoryTextColor': const Color(0xFFF5222D),
            'artworkName': '《百鸟朝凤》',
            'volume': '756',
            'change': '+5.2%',
          },
          {
            'name': '东阳木雕精品',
            'author': '赵强',
            'price': '32500',
            'ranking': 4,
            'tradeType': 'buy',
            'imageUrl': 'assets/images/nft/wood_carving.svg',
            'category': '木雕',
            'categoryText': '木雕',
            'categoryBgColor': const Color(0xFFF0FFF4),
            'categoryTextColor': const Color(0xFF52C41A),
            'artworkName': '《松鹤延年》',
            'volume': '432',
            'change': '+3.1%',
          },
          {
            'name': '古琴艺术传承',
            'author': '孙文',
            'price': '46800',
            'ranking': 5,
            'tradeType': 'buy',
            'imageUrl': 'assets/images/nft/guqin_music.svg',
            'category': '古琴',
            'categoryText': '古琴',
            'categoryBgColor': const Color(0xFFF6F0FF),
            'categoryTextColor': const Color(0xFF722ED1),
            'artworkName': '《高山流水》',
            'volume': '298',
            'change': '+1.8%',
          },
          {
            'name': '惠山泥人艺术',
            'author': '周明',
            'price': '12600',
            'ranking': 6,
            'tradeType': 'buy',
            'imageUrl': 'assets/images/nft/huishan_clay_art.svg',
            'category': '泥塑',
            'categoryText': '泥塑',
            'categoryBgColor': const Color(0xFFE6F7FF),
            'categoryTextColor': const Color(0xFF1890FF),
            'artworkName': '《吉祥娃娃》',
            'volume': '186',
            'change': '+0.9%',
          },
          // 新增拍卖类型藏品1
          {
            'name': '明代青花瓷拍卖',
            'author': '古董收藏家',
            'price': '85000',
            'ranking': 7,
            'tradeType': 'auction',
            'imageUrl': 'assets/images/nft/ceramic_culture.svg',
            'category': '陶瓷',
            'categoryText': '陶瓷',
            'categoryBgColor': const Color(0xFFFFF7E0),
            'categoryTextColor': const Color(0xFFFA8C16),
            'artworkName': '《明青花龙纹瓶》',
            'endTime': '2024-02-15 18:00',
            'bidCount': 23,
            'timeLeft': '2天3小时',
          },
          // 新增拍卖类型藏品2
          {
            'name': '清代刺绣屏风',
            'author': '宫廷艺术',
            'price': '62000',
            'ranking': 8,
            'tradeType': 'auction',
            'imageUrl': 'assets/images/nft/qing_embroidery_screen.svg',
            'category': '刺绣',
            'categoryText': '刺绣',
            'categoryBgColor': const Color(0xFFE6F7FF),
            'categoryTextColor': const Color(0xFF1890FF),
            'artworkName': '《凤凰牡丹屏风》',
            'endTime': '2024-02-16 20:00',
            'bidCount': 18,
            'timeLeft': '3天5小时',
          },
        ];
        _filteredNfts = nfts;
        _isLoading = false;
        });
      }
    });
  }

  // 筛选NFT
  void _filterNFTs(String filter) {
    setState(() {
      _selectedFilter = filter;
      _applyFilters();
    });
  }

  // 搜索NFT
  void _searchNFTs(String searchText) {
    setState(() {
      _searchText = searchText;
      _applyFilters();
    });
  }

  // 应用筛选和搜索
  void _applyFilters() {
    if (_isLoading) return;

    List<Map<String, dynamic>> result = List.from(nfts);

    // 应用筛选
    if (_selectedFilter != '全部') {
      result = result
          .where((nft) => nft['category'] == _selectedFilter)
          .toList();
    }

    // 应用搜索
    if (_searchText.isNotEmpty) {
      final lowerSearchText = _searchText.toLowerCase();
      result = result
          .where((nft) => 
              nft['name'].toLowerCase().contains(lowerSearchText) ||
              nft['author'].toLowerCase().contains(lowerSearchText))
          .toList();
    }

    _filteredNfts = result;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: const Color(0xFFF8F9FA),
      child: Column(
        children: [
          // 排名类型切换
          Container(
            margin: const EdgeInsets.fromLTRB(20, 16, 20, 0),
            child: Row(
              children: [
                Text(
                  '排名类型：',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF666666),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        _buildRankingButton('价格排名'),
                        _buildRankingButton('交易量排名'),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 筛选栏
          Container(
            margin: const EdgeInsets.fromLTRB(20, 16, 20, 0),
            width: double.infinity,
            height: 40,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  spreadRadius: 0,
                  blurRadius: 4,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: ['全部', '苏绣', '陶瓷', '剪纸', '木雕', '古琴', '泥塑'].length,
              itemBuilder: (context, index) {
                final label = ['全部', '苏绣', '陶瓷', '剪纸', '木雕', '古琴', '泥塑'][index];
                return Container(
                  margin: const EdgeInsets.symmetric(horizontal: 5),
                  child: GestureDetector(
                    onTap: () => _filterNFTs(label),
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 15),
                      child: Center(
                        child: Text(
                          label,
                          style: TextStyle(
                            fontSize: 14,
                            color: _selectedFilter == label ? const Color(0xFF1890FF) : const Color(0xFF666666),
                            fontWeight: _selectedFilter == label ? FontWeight.bold : FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),

          // 搜索栏
          Container(
            margin: const EdgeInsets.fromLTRB(20, 16, 20, 0),
            width: double.infinity,
            height: 40,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: const Color(0xFFF0F2F5),
            ),
            child: Row(
              children: [
                // 搜索图标
                Container(
                  margin: const EdgeInsets.only(left: 20),
                  width: 20,
                  height: 20,
                  child: CustomPaint(
                    painter: SearchIconPainter(),
                  ),
                ),
                // 搜索文本框
                Expanded(
                  child: TextField(
                    onChanged: _searchNFTs,
                    decoration: InputDecoration(
                      hintText: '搜索NFT藏品',
                      hintStyle: const TextStyle(
                        fontSize: 14,
                        color: Color(0xFF9CA3AF),
                      ),
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.only(left: 15, top: 10),
                    ),
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: 20),

          // NFT列表
          Expanded(
            child: _isLoading 
              ? _buildLoadingState()
              : _filteredNfts.isEmpty
                ? _buildEmptyState()
                : ListView.builder(
                    padding: const EdgeInsets.all(20),
                    shrinkWrap: true,
                    physics: const BouncingScrollPhysics(),
                    itemCount: _filteredNfts.length,
                    itemBuilder: (context, index) {
                      final nft = _filteredNfts[index];
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 20.0),
                        child: FadeInAnimation(
                          delay: index * 0.1,
                          child: _buildNFTCard(nft, context),
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }



  // 加载状态组件
  Widget _buildLoadingState() {
    return Container(
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            color: const Color(0xFF1890FF),
            strokeWidth: 2,
          ),
          const SizedBox(height: 12),
          Text(
            '加载NFT数据中...',
            style: TextStyle(
              fontSize: 14,
              color: Color(0xFF666666),
            ),
          ),
        ],
      ),
    );
  }

  // 空状态组件
  Widget _buildEmptyState() {
    return Container(
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.collections,
            size: 60,
            color: const Color(0xFFE0E0E0),
          ),
          const SizedBox(height: 16),
          Text(
            '暂无NFT藏品',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '尝试调整筛选条件或搜索其他藏品',
            style: TextStyle(
              fontSize: 14,
              color: Color(0xFF999999),
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              // 重置筛选和搜索
              _selectedFilter = '全部';
              _searchText = '';
              _applyFilters();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF1890FF),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),
              elevation: 0,
            ),
            child: const Text(
              '重置筛选',
              style: TextStyle(
                fontSize: 14,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 筛选按钮 - 优化交互和样式
  Widget _buildFilterButton(String label) {
    final bool isSelected = label == _selectedFilter;
    
    return Container(
      margin: const EdgeInsets.only(right: 12),
      child: ElevatedButton(
        onPressed: () {
          // 添加点击效果
          _filterNFTs(label);
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: isSelected ? const Color(0xFF1890FF) : Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
            side: BorderSide(
              color: isSelected ? const Color(0xFF1890FF) : const Color(0xFFE0E0E0),
              width: 1,
            ),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : const Color(0xFF666666),
            fontSize: 14,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildNFTCard(Map<String, dynamic> nft, BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 4,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // NFT图片区域
          Container(
            width: double.infinity,
            height: 200,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: nft['categoryBgColor'],
            ),
            child: Stack(
              children: [
                // 图片加载逻辑
                ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: SvgPicture.asset(
                    nft['imageUrl'],
                    width: double.infinity,
                    height: 200,
                    fit: BoxFit.cover,
                    placeholderBuilder: (context) => Container(
                      color: nft['categoryBgColor'],
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              nft['categoryText'],
                              style: TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                                color: nft['categoryTextColor'],
                              ),
                            ),
                            Text(
                              nft['artworkName'],
                              style: TextStyle(
                                fontSize: 14,
                                color: nft['categoryTextColor'],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // NFT信息区域
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // NFT名称
                Text(
                  nft['name'],
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333),
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 8),
                // 作者和价格横向排列
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        '作者: ${nft['author']}',
                        style: const TextStyle(
                          fontSize: 14,
                          color: Color(0xFF666666),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Text(
                      '${_formatPrice(nft['price'])} USDT',
                      style: const TextStyle(
                        fontSize: 14,
                        color: Color(0xFF1890FF),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 6),
                
                // 排名和交易数据
                if (nft['ranking'] != null) ...[
                  Row(
                    children: [
                      Text(
                        '排名: #${nft['ranking']}',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF1890FF),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      if (nft['volume'] != null) ...[
                        const SizedBox(width: 12),
                        Text(
                          '交易量: ${nft['volume']}',
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0xFF666666),
                          ),
                        ),
                      ],
                    ],
                  ),
                  const SizedBox(height: 4),
                  if (nft['change'] != null)
                    Text(
                      '24h涨跌: ${nft['change']}',
                      style: TextStyle(
                        fontSize: 12,
                        color: nft['change'].startsWith('+') 
                            ? const Color(0xFF52C41A) 
                            : const Color(0xFFFF4D4F),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                ],
                
                const SizedBox(height: 12),
                // 交易按钮
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {
                      if (nft['tradeType'] == 'auction') {
                        // 跳转到NFT拍卖页面
                        Navigator.pushNamed(context, '/nft_auction', arguments: nft);
                      } else {
                        // 跳转到NFT交易确认页面
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => NFTTransactionConfirmScreen(
                              nftData: nft,
                            ),
                          ),
                        );
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: nft['tradeType'] == 'auction' 
                          ? const Color(0xFFFF6B35) 
                          : const Color(0xFF1890FF),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 12,
                      ),
                      elevation: 0,
                      shadowColor: Colors.transparent,
                    ),
                    child: Text(
                      nft['tradeType'] == 'auction' ? '立即竞拍' : '立即购买',
                      style: const TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 格式化价格
  String _formatPrice(String price) {
    try {
      final double value = double.parse(price);
      return value.toStringAsFixed(0).replaceAllMapped(
        RegExp(r'\B(?=(\d{3})+(?!\d))'),
        (Match m) => ',',
      );
    } catch (e) {
      return price;
    }
  }

  // 构建排名按钮
  Widget _buildRankingButton(String label) {
    final bool isSelected = label == _rankingType;
    
    return Container(
      margin: const EdgeInsets.only(right: 12),
      child: GestureDetector(
        onTap: () => _switchRankingType(label),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFF1890FF) : Colors.white,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(
              color: isSelected ? const Color(0xFF1890FF) : const Color(0xFFE0E0E0),
              width: 1,
            ),
          ),
          child: Text(
            label,
            style: TextStyle(
              color: isSelected ? Colors.white : const Color(0xFF666666),
              fontSize: 12,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }
}

// 淡入动画组件
class FadeInAnimation extends StatefulWidget {
  final Widget child;
  final double delay;

  const FadeInAnimation({
    Key? key,
    required this.child,
    this.delay = 0.0,
  }) : super(key: key);

  @override
  State<FadeInAnimation> createState() => _FadeInAnimationState();
}

class _FadeInAnimationState extends State<FadeInAnimation> 
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _opacityAnimation;
  late Animation<double> _translateAnimation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );

    _opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeOut,
      ),
    );

    _translateAnimation = Tween<double>(begin: 20.0, end: 0.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeOut,
      ),
    );

    // 添加延迟
    Future.delayed(Duration(milliseconds: (widget.delay * 1000).toInt()), () {
      if (mounted) {
        _controller.forward();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Opacity(
          opacity: _opacityAnimation.value,
          child: Transform.translate(
            offset: Offset(0, _translateAnimation.value),
            child: child,
          ),
        );
      },
      child: widget.child,
    );
  }
}

// 图片淡入组件
class FadeInImage extends StatefulWidget {
  final Widget image;

  const FadeInImage({Key? key, required this.image}) : super(key: key);

  @override
  State<FadeInImage> createState() => _FadeInImageState();
}

class _FadeInImageState extends State<FadeInImage> 
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _opacityAnimation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    _opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeInOut,
      ),
    );

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Opacity(
          opacity: _opacityAnimation.value,
          child: child,
        );
      },
      child: widget.image,
    );
  }
}

// 返回箭头绘制器
class BackArrowPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = const Color(0xFF666666)
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    final path = Path();
    path.moveTo(size.width * 0.8, size.height * 0.5);
    path.lineTo(size.width * 0.2, size.height * 0.5);
    path.moveTo(size.width * 0.2, size.height * 0.5);
    path.lineTo(size.width * 0.5, size.height * 0.2);
    path.moveTo(size.width * 0.2, size.height * 0.5);
    path.lineTo(size.width * 0.5, size.height * 0.8);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

// 搜索图标绘制器
class SearchIconPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = const Color(0xFFC9CDD4)
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    // 绘制圆形
    canvas.drawCircle(
      Offset(size.width * 0.5, size.height * 0.5),
      size.width * 0.4,
      paint,
    );

    // 绘制直线
    canvas.drawLine(
      Offset(size.width * 0.7, size.height * 0.7),
      Offset(size.width * 0.9, size.height * 0.9),
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}